<?php
/*
*	$version: 2009-5-19 pm 12:30:21 beta 1.0
*	$id: cacheFactory.php 
*	$author: taoFeng
*	$mailto: font99@Gmail.com
*	$license: This is not a freeware
*/

if (!defined('IN_LEKO')) {header("HTTP/1.0 403 Forbidden");exit;}

define('CACHEDATA', 0);
define('CACHEDATE', 1);

class cacheFactory {

	function setCache($k ,$sql, $ttl = 0){
		global $_G,$_C,$_D;

		$a_result = array();
		
		if (empty($sql)) return false;

		$o_query = $_D->Query($sql);
		
		if ($o_query){
			if ($_D->getNumrows() == 1){
				$a_result = $_D->fetchRow($o_query);
			}
			elseif ($_D->sqlNumrows() > 1){
				$a_result = $_D->fetchRowset($o_query);
			}
			else
				return false;

			if (is_array($a_result) && count($a_result)){
				$_C->_setCache($k,serialize($a_result),$ttl);
				return $a_result;
			}
		}
		else
			return false;
	}

	function getCache($id , $type , $sql = '' , $ttl = 0 , $force = 0){ //这里可以按照PID更新 按照时间更新
		global $_C;

		$s_key = '';

		$a_cache = $p_cache = array();

		$s_pid = md5($id.$type."_pid");

		if ($force) $s_key = md5($id.$type); else $s_key = md5($id.$type.$sql);

		if ($ttl > 0){ //按照时间更新

			$a_cache = $_C->_getCache($s_key);

			if (!is_array($a_cache)){
				$o_result = $this->setCache($s_key,$sql,$ttl);
				if (!$o_result) return false; else return $o_result;
			}
			else{
				return unserialize($a_cache[CACHEDATA]);
			}
		}
		else{ //按照PID更新

			$p_cache = $_C->_getCache($s_pid);

			if (!$p_cache) {//PID不存在，就生成
				$_C->_setCache($s_pid,'1');
				$p_cache = $_C->_getCache($s_pid);
				$p_time = $p_cache[CACHEDATE];
			}
			else{
				$p_time = $p_cache[CACHEDATE];
			}

			$a_cache = $_C->_getCache($s_key);

			if ($p_time > $a_cache[CACHEDATE]){
				$o_result = $this->setCache($s_key,$sql);
				if (!$o_result) return false; else return $o_result;
			}
			else{
				return unserialize($a_cache[CACHEDATA]);
			}
		}
	}

	function touchCache($id,$type){
		global $_C;

		$pid = md5($id.$type."_pid");

		@$_C->_touchCache($pid);
	}

}

?>